import threading
import queue
import time
from enum import Enum
from typing import List, Dict
from datetime import datetime

class AutoPublishStatus(Enum):
    STOPPED = 0
    RUNNING = 1
    PAUSED = 2

class AutoPublishManager:
    def __init__(self):
        self._status = AutoPublishStatus.STOPPED
        self._task_queue = queue.Queue()
        self._worker_thread = None
        self._lock = threading.Lock()
        self._callbacks = []

    def start(self):
        """开始自动发布流程"""
        with self._lock:
            if self._status != AutoPublishStatus.STOPPED:
                return False
            
            self._status = AutoPublishStatus.RUNNING
            self._worker_thread = threading.Thread(target=self._worker_loop)
            self._worker_thread.daemon = True
            self._worker_thread.start()
            
            self._notify_status_change("自动发布已启动")
            return True

    def stop(self):
        """停止自动发布流程"""
        with self._lock:
            if self._status == AutoPublishStatus.STOPPED:
                return False
            
            self._status = AutoPublishStatus.STOPPED
            if self._worker_thread:
                self._worker_thread.join()
                self._worker_thread = None
            
            # 清空任务队列
            while not self._task_queue.empty():
                self._task_queue.get()
            
            self._notify_status_change("自动发布已停止")
            return True

    def pause(self):
        """暂停自动发布流程"""
        with self._lock:
            if self._status != AutoPublishStatus.RUNNING:
                return False
            
            self._status = AutoPublishStatus.PAUSED
            self._notify_status_change("自动发布已暂停")
            return True

    def resume(self):
        """恢复自动发布流程"""
        with self._lock:
            if self._status != AutoPublishStatus.PAUSED:
                return False
            
            self._status = AutoPublishStatus.RUNNING
            self._notify_status_change("自动发布已恢复")
            return True

    def _worker_loop(self):
        """工作线程主循环"""
        while self._status != AutoPublishStatus.STOPPED:
            if self._status == AutoPublishStatus.PAUSED:
                time.sleep(1)
                continue

            try:
                # 尝试获取任务，设置超时以便能够响应状态变化
                task = self._task_queue.get(timeout=1)
                self._process_task(task)
            except queue.Empty:
                continue
            except Exception as e:
                self._notify_error(f"处理任务时出错: {str(e)}")

    def _process_task(self, task: Dict):
        """处理单个发布任务"""
        try:
            # 1. 获取视频内容
            video_path = task.get('video_path')
            if not video_path:
                raise ValueError("未指定视频路径")

            # 2. 准备发布内容
            platforms = task.get('platforms', [])
            if not platforms:
                raise ValueError("未指定发布平台")

            # 3. 执行发布
            for platform in platforms:
                self._publish_to_platform(platform, video_path, task)

            # 4. 更新任务状态
            self._notify_success(f"视频 {video_path} 发布完成")

        except Exception as e:
            self._notify_error(f"发布失败: {str(e)}")

    def _publish_to_platform(self, platform: str, video_path: str, task: Dict):
        """发布到指定平台"""
        # TODO: 实现具体平台的发布逻辑
        pass

    def add_task(self, task: Dict):
        """添加发布任务到队列"""
        self._task_queue.put(task)
        self._notify_info(f"已添加新的发布任务")

    def register_callback(self, callback):
        """注册状态回调函数"""
        self._callbacks.append(callback)

    def _notify_status_change(self, message: str):
        """通知状态变化"""
        for callback in self._callbacks:
            callback({
                'type': 'status',
                'message': message,
                'status': self._status,
                'timestamp': datetime.now()
            })

    def _notify_error(self, message: str):
        """通知错误信息"""
        for callback in self._callbacks:
            callback({
                'type': 'error',
                'message': message,
                'timestamp': datetime.now()
            })

    def _notify_success(self, message: str):
        """通知成功信息"""
        for callback in self._callbacks:
            callback({
                'type': 'success',
                'message': message,
                'timestamp': datetime.now()
            })

    def _notify_info(self, message: str):
        """通知一般信息"""
        for callback in self._callbacks:
            callback({
                'type': 'info',
                'message': message,
                'timestamp': datetime.now()
            })

    @property
    def status(self) -> AutoPublishStatus:
        """获取当前状态"""
        return self._status
